"""
嘴巴动作

@author:HXP
@date:2018-3-5

"""

import serial
import time
import codecs
import random
import threading
import general_action
from emotion_control import happy, unhappy
from emotion_rec import get_emotion

ser = serial.Serial('/dev/HLF_HEAD', 115200, timeout=0.1)  # 初始化串口


# 面部动作
def face_action(text):
    # 情绪动作线程
    emotion_thread = threading.Thread(target=emotion, name='Thread-Emotion', args=(text,))
    emotion_thread.start()
    # 最后两位十进制 90(闭合)——130(最开)
    ser.write(codecs.decode('0200110000', 'hex_codec'))  # 嘴巴舵机速度
    time.sleep(0.005)
    for i in range(1, len(text)):
        # 眼睛动作
        if i % 4 == 0:
            eye_thread = threading.Thread(target=general_action.eye_action, name='Thread-Eye')
            eye_thread.start()
        # 眼珠动作
        if i % 5 == 0:
            eyeball_thread = threading.Thread(target=general_action.eyeball_action, name='Thread-Eyeball')
            eyeball_thread.start()
        # 嘴部动作
        r1 = random.randint(100, 110)
        r2 = random.randint(110, 120)
        ser.write(codecs.decode(('02001000' + hex(r1)[2:]), 'hex_codec'))  # 嘴巴复位
        time.sleep(0.1)
        ser.write(codecs.decode(('02001000' + hex(r2)[2:]), 'hex_codec'))  # 嘴巴张开
        time.sleep(0.1)
    # 头部复位
    general_action.reset()


def mouth_reset():
    ser.write(codecs.decode('0200110000', 'hex_codec'))  # 嘴巴舵机速度
    time.sleep(0.005)
    ser.write(codecs.decode(('02001000' + hex(100)[2:]), 'hex_codec'))  # 嘴巴复位
    time.sleep(0.005)


def emotion(text):
    print('情绪识别')
    # 识别情绪
    if get_emotion(text) == 1:
        happy()
    else:
        unhappy()


def eye():
    print('眼部动作')
    general_action.eye_action()
    general_action.eyeball_action()
